package com.ailanyin.admin.controller;

import com.ailanyin.admin.service.CommonFileService;
import com.ailanyin.common.result.AjaxResult;
import com.ailanyin.common.utils.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/25 0025 上午 11:13
 */
@RestController
@Api(tags = "通用文件上传下载")
public class CommonFileController {

    @Autowired
    private CommonFileService commonFileService;

    @ApiOperation(value = "文件下载")
    @GetMapping("common/download")
    public void fileDownload(String fileName, HttpServletResponse response) throws Exception {
        String realFileName = fileName.substring(fileName.indexOf("_") + 1);
        String filePath = FileUtil.getDownloadPath() + fileName;
        FileUtil.setAttachmentResponseHeader(response, realFileName);
        FileUtil.writeBytes(filePath, response.getOutputStream());
        FileUtil.deleteFile(filePath);
    }

    @PostMapping("common/upload")
    @ApiOperation(value = "文件上传")
    public AjaxResult fileUpload(MultipartFile file) {
        return AjaxResult.success(commonFileService.fileUpload(file));
    }
}
